<template>
  <BdpLayout>
    <page-header
      button-permission="bdp:dcs:IndustrialDataCollection:add"
      search-keywords="名称"
      type="add-search"
      @click="addDbClick"
      @search="onSearch"
    >
    </page-header>
    <b-table
      :columns="columns"
      :data-source="dbList"
      :is-custom-row-click="false"
      :loading="listLoading"
      :pagination="pagination"
      style="height: calc(100% - 40px)"
      @change="handleTableChange"
    >
      <template #fileCount="{ text, record }">
        <a-button type="link" @click="fileClick(record)">
          <a-icon type="file"></a-icon>
          {{ record.fileCount }}
        </a-button>
      </template>
      <template #cron="{ text, record }">
        <a-button v-if="record.cron" type="link" @click="addTaskClick(record)">
          <a-icon type="clock-circle"></a-icon>
          {{ parseCron(record.cron) }}
        </a-button>
        <a-button v-else type="link" @click="addTaskClick(record)">
          <a-icon type="add"></a-icon>
          定时备份
        </a-button>
      </template>
      <template #action="{ text, record }">
        <a-button type="link" @click="backupClick(record)"> 备份</a-button>
        <a-button type="link" @click="editDbClick(record)"> 编辑</a-button>
        <a-button type="link" @click="deleteDbClick(record)"> 删除</a-button>
      </template>
    </b-table>

    <DbForm v-if="dbFormShow" ref="dbFormRef" @close="closeDbForm()" @success="getDbList"></DbForm>
    <dbRestoreModal
      v-if="restoreModalShow"
      ref="restoreModalRef"
      @close="closeRestoreModal()"
      @success="getDbList"
    ></dbRestoreModal>
    <TaskForm v-if="taskFormShow" ref="taskFormRef" @close="closeTaskForm()" @success="getDbList"></TaskForm>
    <FileList v-if="fileListShow" ref="fileListRef" @close="closeFileList()" @success="getDbList"></FileList>
  </BdpLayout>
</template>

<script>
import { VXETable } from 'vxe-table/lib/v-x-e-table';
import DbForm from '@/pages/bdp/sl/dataSecurity/dbForm.vue';
import TaskForm from '@/pages/bdp/sl/dataSecurity/taskForm.vue';
import FileList from '@/pages/bdp/sl/dataSecurity/fileList.vue';
import DbRestoreModal from '@/pages/bdp/sl/dataSecurity/dbRestoreModal.vue';
import { dataBackupColumns2 } from '@bdp/sl/utils/columns';
import { backup, deleteDatabase, getDbList } from '@bdp/sl/dataSecurity/api';

export default {
  components: { DbRestoreModal, DbForm, TaskForm, FileList },
  data() {
    return {
      columns: Object.freeze(dataBackupColumns2),
      dbList: [],
      taskList: [],
      listLoading: false,
      restoreModalShow: false,
      taskListLoading: false,
      dbFormShow: false,
      taskFormShow: false,
      fileListShow: false,
      backupLoading: false,
      weeklyList: [
        { label: '周一', value: '2' },
        { label: '周二', value: '3' },
        { label: '周三', value: '4' },
        { label: '周四', value: '5' },
        { label: '周五', value: '6' },
        { label: '周六', value: '7' },
        { label: '周日', value: '1' },
      ],
      pagination: {
        current: 1,
        pageSize: 20,
        total: 0,
      },
    };
  },
  mounted() {
    this.getDbList();
  },
  methods: {
    /* 表格翻页 */
    handleTableChange({ pagination }) {
      this.pagination = pagination;
      this.getDbList();
    },
    onSearch() {},
    // 获取数据库列表
    getDbList(unloading) {
      this.listLoading = !unloading;
      getDbList()
        .then((res) => {
          this.dbList = res.data;
          this.listLoading = false;
        })
        .catch(() => {
          this.listLoading = false;
        });
    },
    // 新建连接
    addDbClick() {
      this.dbFormShow = true;
      this.$nextTick(() => {
        this.$refs.dbFormRef.init(false, null);
      });
    },
    // 编辑连接
    editDbClick(row) {
      this.dbFormShow = true;
      this.$nextTick(() => {
        this.$refs.dbFormRef.init(true, row);
      });
    },
    // 备份
    async backupClick(row) {
      const type = await VXETable.modal.confirm({
        content: `您确认要备份【${row.dbName}】吗？`,
        escClosable: true,
      });
      if (type === 'confirm') {
        this.backupLoading = true;
        VXETable.modal.message({
          id: `backupMsg${row.id}`,
          content: `正在备份【${row.dbName}】`,
          status: 'loading',
          duration: -1,
        });
        backup(row.id)
          .then((res) => {
            if (res.code === 0) {
              VXETable.modal.message({ content: `【${row.dbName}】备份成功`, status: 'success' });
              this.getDbList();
            }
            this.backupLoading = false;
            VXETable.modal.close(`backupMsg${row.id}`);
          })
          .catch(() => {
            this.backupLoading = false;
            VXETable.modal.close(`backupMsg${row.id}`);
          });
      }
    },
    // 还原
    restoreCheckClick(row) {
      this.restoreModalShow = true;
      this.$nextTick(() => {
        this.$refs.restoreModalRef.init(row);
      });
    },
    // 添加定时备份
    addTaskClick(row) {
      this.taskFormShow = true;
      this.$nextTick(() => {
        this.$refs.taskFormRef.init(row);
      });
    },
    // 删除任务
    async deleteDbClick(row) {
      const type = await VXETable.modal.confirm({
        content: `您确认要删除连接【${row.dbName}】吗？`,
        escClosable: true,
      });
      if (type === 'confirm') {
        deleteDatabase(row.id).then((res) => {
          VXETable.modal.message({ content: `【${row.dbName}】删除成功`, status: 'success' });
          this.getDbList();
        });
      }
    },
    // 备份文件
    fileClick(row) {
      this.fileListShow = true;
      this.$nextTick(() => {
        this.$refs.fileListRef.init(row);
      });
    },
    closeDbForm() {
      this.dbFormShow = false;
    },
    closeTaskForm() {
      this.taskFormShow = false;
      this.getDbList();
    },
    closeFileList() {
      this.fileListShow = false;
      this.getDbList();
    },
    closeRestoreModal() {
      this.restoreModalShow = false;
      this.getDbList();
    },
    // 解析cron表达式
    parseCron(cron) {
      const parts = cron.split(' ');
      if (parts.length !== 6 && parts.length !== 7) {
        return;
      }
      const [second, minute, hour, day, month, dayOfWeek, year] = parts;
      const time = ' ' + hour + ':' + minute + ':' + second;
      let cycle;
      if (month !== '*' && day !== '*' && dayOfWeek === '?') {
        cycle = '每年' + month + '月' + day + '日' + time;
      } else if (month === '*' && day !== '*' && dayOfWeek === '?') {
        cycle = '每月' + day + '日' + time;
      } else if (month === '*' && day === '?' && dayOfWeek !== '*') {
        cycle = '每周' + this.weeklyList.filter((x) => x.value === dayOfWeek)[0].label + time;
      } else if (month === '*' && day === '*' && dayOfWeek === '?') {
        cycle = '每日' + time;
      }
      return cycle;
    },
    async uploadDbProgram() {
      const { file } = await VXETable.readFile({
        types: ['zip'],
      });
      // 创建FormData对象来封装文件数据
      let formData = new FormData();
      formData.append('file', file);
      // 显示上传提示
      VXETable.modal.message({ id: 'uploadMsg', content: `正在上传：${file.name}`, status: 'loading', duration: 3000 });
      request({
        url: '/bdp/sl/api/db-backup/upload/db-program',
        method: 'post',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      }).then((res) => {
        if (res.code === 0) {
          VXETable.modal.message({ content: res.message, status: 'success' });
        }
        VXETable.modal.close('uploadMsg');
      });
    },
  },
};
</script>
<style>
.container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
}

.header {
  flex: 0 1 auto;
}

.content {
  flex: 1 1 auto;
}
</style>
